# -*- coding:utf-8 -*-
"""

"""
import requests
import json
from bs4 import BeautifulSoup
import re
from WriteData import writedata
from Tk import genearteMD5
from cs import day


def get_html_text(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
        'accept': 'application/json, text/plain, */*',
        'accept-language': 'zh-CN,zh;q=0.9',
        'origin': 'https://www.coinbull.one',
        'referer': 'https://www.coinbull.one/kuaixun',
        'x-app-info': '2.4.0/offical/web',
    }
    try:
        r = requests.get(url, timeout=30, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except Exception as e:
        print(e)
        return None


def get_dates_kx(url):
    text = get_html_text(url)
    if not text:
        return None
    text = json.loads(text)
    data = text['data']['list']
    soup = BeautifulSoup(data, 'lxml')
    datelist = soup.select('.left-time-star span')
    reg = re.compile(r'(\d*月\d*)日')
    dates = ['2018-' + re.findall(reg, date.get_text())[0].replace('月', '-') for date in datelist]
    return dates


def count_process_one():
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 1
    while a < 50:
        url = 'http://www.yunshi24.com/newsletter/list/{}.html'
        url = url.format(a)
        dates = get_dates_kx(url)
        if not dates:
            continue
        print('----陨石财经快讯获取第{}页----'.format(a))
        for date in dates:
            s = day(date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        a += 1
        if d4 > 0:
            break
    return (d1, d2, d3)


def main():
    u = '陨石财经'
    t1 = count_process_one()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0], "yesterday": t1[1], "frontday": t1[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
